const { Controller } = require("egg");

const path = require("path");
const fs = require("fs");
const cos = require('cos-nodejs-sdk-v5');


class ArticleController extends Controller {
  async importArticleHtmlSingle() {
    const { ctx, service } = this;
    const { url } = ctx.request.body;
    try {
      const res = await service.article.importContent(url);
      this.ctx.helper.success(res);
    } catch (err) {
      console.log(err);
      this.ctx.helper.error(err, "文章创建失败,请重试");
    }
  }

  async importArticlExcel() {
    try {
      const { ctx, service } = this;
      const filePath = path.join(__dirname, "../public/webpath2.xlsx");
      const result = await service.excel.readExcelToJson(filePath);
      const fileName = "output2.json";
      const outputPath = path.join(__dirname, "../public", fileName);

      try {
        const jsonData = JSON.stringify(result, null, 2);
        fs.writeFileSync(outputPath, jsonData, "utf8");

        console.log(`JSON data has been saved to ${outputPath}`);
      } catch (error) {
        console.error("Error writing JSON file:", error);
      }

      this.ctx.helper.success(result);
    } catch (err) {
      return this.ctx.helper.error(err, "文章分类创建失败 请稍后重试");
    }
  }

  async importArticlExcelOld() {
    try {
      const { ctx, service } = this;
      const filePath = path.join(__dirname, "../public/webpath.xlsx");
      const result = await service.excel.readExcelToJson(filePath);
      const fileName = "output.json";
      const outputPath = path.join(__dirname, "../public", fileName);







      try {
        const jsonData = JSON.stringify(result, null, 2);
        fs.writeFileSync(outputPath, jsonData, "utf8");

        console.log(`JSON data has been saved to ${outputPath}`);
      } catch (error) {
        console.error("Error writing JSON file:", error);
      }

      this.ctx.helper.success(result);
    } catch (err) {
      return this.ctx.helper.error(err, "文章分类创建失败 请稍后重试");
    }
  }

  async importDirectory() {
    const fileName = path.join(__dirname, "../public", "output2.json");
    const data = fs.readFileSync(fileName, "utf8");
    const json = JSON.parse(data);
    const mapInfo = [];
    const { service } = this;

    try {
      for (const file of json) {
        const { category } = file;
        const lastDirectoryInfo = await service.directory.createDirectories(
          category
        );

        mapInfo.push(lastDirectoryInfo);
      }
      this.ctx.helper.success(mapInfo);
    } catch (error) {
      return this.ctx.helper.error(error, "文章分类创建失败 请稍后重试");
    }
  }

  async importArticleArr() {
    const fileName = path.join(__dirname, "../public", "output2.json");
    const data = fs.readFileSync(fileName, "utf8");
    const json = JSON.parse(data);
    this.handleData(json);
    this.ctx.helper.success(json);
  }

  findDirectoryByName(categoryList, nameList) {
    const isSecond = nameList.length === 2;
    const isThird = nameList.length === 3;
    const first = categoryList.find((item) => item.name === nameList[0]);
    const second = first.children.find(
      (item) => item.name === nameList[1]
    );
    if (isSecond) {
      return second;
    }

    if (isThird) {
      return second.children.find(
        (item) => item.name === nameList[2]
      );
    }


  }

  async handleData(json) {
    const { article, directory, directoryArticle } = this.service;

    const categoryAll = await directory.list();

    for (const file of json) {
      const { url, category } = file;
      const directoryInfo = this.findDirectoryByName(categoryAll, category)

      if (!directoryInfo) {
        throw new Error(`栏目 ${category[category.length - 1]}不存在`);
      }
      try {
        const { id } = await article.importContent(url);
        const articleId = id;
        const directoryId = directoryInfo.id;

        await directoryArticle.bind({ articleId, directoryId });
        this.ctx.logger.info(file);
      } catch (error) {
        this.ctx.logger.error(error); // 如果排不到这个数据就舍弃
      }
    }
  }

  async importPersonCertificates() {
    try {
      const { ctx, service } = this;
      const filePath = path.join(__dirname, "../public/个人证书信息.xlsx");
      const result = await service.excel.readExcelToJsonBase(filePath);
      const [, ...datas] = result;
      for (let data of datas) {
        const [name, gender, idNumber, certificateName, certificateNumber, certificateLevel, workUnit, position] = data;
        console.log(data, "data")
        if (name) {

          const params = {
            isDeleted: 0,
            name,
            gender,
            idNumber,
            certificateName,
            certificateNumber,
            certificateLevel,
            workUnit,
            position,
            createAt: null,
            updateAt: null
          }
          await this.service.personCertificate.create(params)

        }

      }
      this.ctx.helper.success(result);

    } catch (err) {
      return this.ctx.helper.error(err);
    }
  }


  async importEnterpriseCertificates() {



    const isValidDate = (date) => {
      try {
        date = new Date(date)
        return date instanceof Date && !isNaN(date)
      } catch (error) {
        return false
      }
    }




    try {
      const { ctx, service } = this;
      const filePath = path.join(__dirname, "../public/企业.xlsx");
      const result = await service.excel.readExcelToJsonBase(filePath);
      const [, ...datas] = result;
      const arrs = []
      for (let arr of datas) {


        if (arr[4] || arr[6]) {
          let [enterpriseName, , , nationalLevel, , certificateTypeName, , annualInspectionYears, validityStartDate, validityEndDate, remarks] = arr;



          try {
            validityStartDate = new Date(validityStartDate)
          } catch {
            validityStartDate = ""
          }
          try {
            validityEndDate = new Date(validityEndDate)
          } catch {
            validityEndDate = ""
          }


          try {
            annualInspectionYears = annualInspectionYears.split("√") || [];

            if (validityStartDate) {
              const time = this.ctx.helper.formatDate(validityStartDate, 'MM-dd');

              const arr = []

              annualInspectionYears.forEach(element => {
                if (element) {
                  arr.push(`${element}-${time}`)
                  return element + '-' + time;
                }
              });

              annualInspectionYears = arr

            }

          } catch (error) {

          }

          const params = {
            enterpriseName,
            nationalLevel,
            certificateTypeName: certificateTypeName || "",
            certificateNumber: arr[6] || arr[4],
            annualInspectionYears: annualInspectionYears || [],
            remarks: remarks || ""
          }
          if (isValidDate(validityStartDate)) {
            params.validityStartDate = validityStartDate
          }

          if (isValidDate(validityEndDate)) {
            params.validityEndDate = validityEndDate
          }

          if (arr[4]) {
            params.certificateNumber = arr[4]
            await this.service.enterpriseCertificate.createOrUpdate(params)
          }
          if (arr[6]) {
            params.certificateNumber = arr[6]
            await this.service.enterpriseCertificate.createOrUpdate(params)
          }
        }

      }

      this.ctx.helper.success(arrs);


    } catch (err) {
      return this.ctx.helper.error(err);
    }
  }


}

module.exports = ArticleController;
